<template>
  <j-modal
    :title="title"
    :width="width"
    :visible="visible"
    :confirmLoading="confirmLoading"
    :keyboard="false"
    :forceRender="true"
    v-bind:prefixNo="prefixNo"
    fullscreen
    switchFullscreen
    @cancel="handleCancel"
    :id="prefixNo"
    style="top: 20px; height: 95%"
  >
    <template slot="footer">
      <a-button @click="handleCancel">取消</a-button>
      <a-button v-if="billPrintFlag && isShowPrintBtn" @click="handlePrint('销售退货入库')">三联打印预览</a-button>
      <a-button v-if="checkFlag && isCanCheck" :loading="confirmLoading" @click="handleOkAndCheck">保存并审核</a-button>
      <a-button type="primary" :loading="confirmLoading" @click="handleOk">保存（Ctrl+S）</a-button>
      <!--发起多级审核-->
      <a-button v-if="!checkFlag" @click="handleWorkflow()" type="primary">提交流程</a-button>
    </template>
    <a-spin :spinning="confirmLoading">
      <a-form :form="form">
        <a-row class="form-row" :gutter="24">
          <a-col :lg="6" :md="12" :sm="24">
            <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="客户">
              <a-select
                placeholder="请选择客户"
                v-decorator="['customerId', validatorRules.customerId]"
                :disabled="!rowCanEdit"
                :dropdownMatchSelectWidth="false"
                showSearch
                optionFilterProp="children"
                @change="handleOrganChange"
              >
                <a-select-option v-for="(item, index) in cusList" :key="index" :value="item.id">
                  {{ item.name }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
               <a-col :lg="6" :md="12" :sm="24">
            <a-form-item
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              label="销售人员"
              data-step="3"
              data-title="销售人员"
            >
              <a-select
                placeholder="请选择销售人员"
                showSearch
                optionFilterProp="children"
                v-decorator="['salespersonId', validatorRules.salespersonId]"
              >
                <a-select-option v-for="(item, index) in userList" :key="index" :value="item.id">
                  {{ item.name }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :lg="6" :md="12" :sm="24">
            <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="单据日期">
              <j-date v-decorator="['operTime', validatorRules.operTime]"  />
            </a-form-item>
          </a-col>
          <a-col :lg="6" :md="12" :sm="24">
            <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="单据编号">
              <a-input placeholder="请输入单据编号" v-decorator.trim="['orderNo']" />
            </a-form-item>
          </a-col>

      
          <a-col :lg="6" :md="50" :sm="24">
            <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="客户地址">
              <a-input placeholder="请输入客户地址" v-decorator.trim="['customerAddress']" />
            </a-form-item>
          </a-col>
          <a-col :md="6" :sm="24">
            <a-form-item label="销货单号" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input placeholder="请选择销货单号" v-model="salesOrderNo" disabled>
                <a-button slot="addonAfter" @click="handPurchaseChoose" icon="plus">选择</a-button>
              </a-input>
            </a-form-item>
          </a-col>
        </a-row>
        <j-editable-table
          id="billModal"
          :ref="refKeys[0]"
          :loading="materialTable.loading"
          :columns="materialTable.columns"
          :dataSource="materialTable.dataSource"
          :minWidth="minWidth"
          :maxHeight="300"
          :rowNumber="false"
          :rowSelection="rowCanEdit"
          :actionButton="rowCanEdit"
          :dragSortAndNumber="rowCanEdit"
          @valueChange="onValueChange"
          @added="onAdded"
          @deleted="onDeleted"
        >
          
        </j-editable-table>
        <a-row class="form-row" :gutter="24">
          <a-col :lg="24" :md="24" :sm="24">
            <a-form-item :labelCol="labelCol" :wrapperCol="{ xs: { span: 24 }, sm: { span: 24 } }" label="">
              <a-textarea :rows="1" placeholder="请输入备注" v-decorator="['remark']" style="margin-top: 8px" />
            </a-form-item>
          </a-col>
        </a-row>
        <a-row class="form-row" :gutter="24">
          <a-col :lg="6" :md="12" :sm="24">
            <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="优惠率">
              <a-input
                style="width: 80%"
                placeholder="请输入优惠率"
                v-decorator.trim="['discountRate']"
                suffix="%"
                @change="onChangeDiscount"
                ref="inputRef"
              />
            </a-form-item>
          </a-col>
          <a-col :lg="6" :md="12" :sm="24">
            <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="退款优惠">
              <a-input
                placeholder="请输入退款优惠"
                v-decorator.trim="['discountAmount']"
                @change="onChangeDiscountMoney"
              />
            </a-form-item>
          </a-col>
          <a-col :lg="6" :md="12" :sm="24">
            <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="优惠后金额">
              <a-input placeholder="请输入优惠后金额" v-decorator.trim="['amountAfterDiscount']" :readOnly="true" />
            </a-form-item>
          </a-col>
     
          <a-col :md="6" :sm="24">
            <a-form-item label="交货方式" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-select
                placeholder="请选择交货方式"
                showSearch
                optionFilterProp="children"
                v-decorator="['deliveryMethod']"
              >
                <a-select-option v-for="(item, index) in deliveryMethodList" :key="index" :value="item">
                  {{ item }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :lg="6" :md="12" :sm="24">
            <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="结算账户">
              <a-select
                style="width: 80%"
                placeholder="请选择结算账户"
                v-decorator="['settlementAccountId', validatorRules.accountId]"
                :dropdownMatchSelectWidth="false"
                allowClear
                @select="selectAccount"
              >
                <a-select-option v-for="(item, index) in accountList" :key="index" :value="item.id">
                  {{ item.name }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :lg="6" :md="12" :sm="24">
            <a-form-item
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              label="物流单号"
              data-step="9"
              data-title="物流单号"
            >
              <a-input placeholder="请输入物流单号" v-decorator.trim="['logisticsNo']" />
            </a-form-item>
          </a-col>
          <a-col :lg="6" :md="12" :sm="24">
            <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="已退款金额">
              <a-input
                placeholder="请输入已退款金额"
                v-decorator.trim="['reReceivedAmount']"
              />
            </a-form-item>
          </a-col>
        </a-row>
      
      </a-form>
    </a-spin>
    <SalesOrderChoose ref="salesOrderChoose" @choose="salesOrderChooseOk"></SalesOrderChoose>
    <many-account-modal ref="manyAccountModalForm" @ok="manyAccountModalFormOk"></many-account-modal>
    <link-bill-list ref="linkBillList" @ok="linkBillListOk"></link-bill-list>
    <customer-modal ref="customerModalForm" @ok="customerModalFormOk"></customer-modal>
    <depot-modal ref="depotModalForm" @ok="depotModalFormOk"></depot-modal>
    <account-modal ref="accountModalForm" @ok="accountModalFormOk"></account-modal>
    <batch-set-depot ref="batchSetDepotModalForm" @ok="batchSetDepotModalFormOk"></batch-set-depot>
    <workflow-iframe ref="modalWorkflow" @ok="workflowModalFormOk"></workflow-iframe>
    <bill-print-iframe ref="modalPrint"></bill-print-iframe>
  </j-modal>
</template>
<script>
import SalesOrderChoose from '../choose/SalesOrderChoose.vue'
import pick from 'lodash.pick'
import ManyAccountModal from '../dialog/ManyAccountModal'
import LinkBillList from '../dialog/LinkBillList'
import CustomerModal from '../../system/modules/CustomerModal'
import DepotModal from '../../system/modules/DepotModal'
import AccountModal from '../../system/modules/AccountModal'
import BatchSetDepot from '../dialog/BatchSetDepot'
import WorkflowIframe from '@/components/tools/WorkflowIframe'
import BillPrintIframe from '../dialog/BillPrintIframe'
import { FormTypes } from '@/utils/JEditableTableUtil'
import { JEditableTableMixin } from '@/mixins/JEditableTableMixin'
import { BillModalMixin } from '../mixins/BillModalMixin'
import { getMpListShort, changeListFmtMinus } from '@/utils/util'
import { getAction } from '@/api/manage'
import JSelectMultiple from '@/components/jeecg/JSelectMultiple'
import JUpload from '@/components/jeecg/JUpload'
import JDate from '@/components/jeecg/JDate'
import Vue from 'vue'
export default {
  name: 'SaleBackModal',
  mixins: [JEditableTableMixin, BillModalMixin],
  components: {
    ManyAccountModal,
    LinkBillList,
    CustomerModal,
    DepotModal,
    AccountModal,
    BatchSetDepot,
    WorkflowIframe,
    BillPrintIframe,
    JUpload,
    JDate,
    JSelectMultiple,
    SalesOrderChoose,
    VNodes: {
      functional: true,
      render: (h, ctx) => ctx.props.vnodes,
    },
  },
  data() {
    return {
      salesOrderId:'',
      salesOrderNo:'',
      title: '操作',
      width: '1600px',
      moreStatus: false,
      // 新增时子表默认添加几行空数据
      addDefaultRowNum: 1,
      visible: false,
      operTimeStr: '',
      prefixNo: 'salesReturn',
      fileList: [],
      rowCanEdit: true,
      model: {},
      labelCol: {
        xs: { span: 24 },
        sm: { span: 8 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 },
      },
      refKeys: ['materialDataTable'],
      activeKey: 'materialDataTable',
      materialTable: {
        loading: false,
        dataSource: [],
        columns: [
          { title: '', key: 'productId', width: '1%', type: FormTypes.hidden },
          {
            title: '编号',
            key: 'productNo',
            width: '12%',
            type: FormTypes.popupJsh,
            kind: 'material',
            multi: true,
            validateRules: [{ required: true, message: '${title}不能为空' }],
          },
          { title: '名称', key: 'productName', width: '10%', type: FormTypes.normal },
          { title: '规格型号', key: 'specificationModel', width: '9%', type: FormTypes.normal },
          { title: '品牌', key: 'brand', width: '6%', type: FormTypes.normal },
          // { title: '供应商', key: 'defaultSupplierName', width: '6%', type: FormTypes.normal },
          { title: '库存', key: 'currentStock', width: '5%', type: FormTypes.normal },
          { title: '单位', key: 'unit', width: '4%', type: FormTypes.normal },
          { title: '单价', key: 'unitPrice', width: '5%', type: FormTypes.inputNumber },
          { title: '折扣率', key: 'discountRate', width: '4%', type: FormTypes.inputNumber, placeholder: '%' },
          {
            title: '折扣额',
            key: 'discountAmount',
            width: '5%',
            type: FormTypes.inputNumber,
            readonly: true,
            statistics: true,
          },
          { title: '折后单价', key: 'amountAfterDiscount', width: '5%', type: FormTypes.inputNumber, readonly: true },
          { title: '税率', key: 'taxRate', width: '4%', type: FormTypes.inputNumber, placeholder: '%' },
          {
            title: '税额',
            key: 'taxAmount',
            width: '5%',
            type: FormTypes.inputNumber,
            readonly: true,
            statistics: true,
          },
          { title: '含税单价', key: 'taxInclusivePrice', width: '5%', type: FormTypes.inputNumber, readonly: true },
                    {
            title: '数量',
            key: 'quantity',
            width: '5%',
            type: FormTypes.inputNumber,
            statistics: true,
            validateRules: [{ required: true, message: '${title}不能为空' }],
          },
          {
            title: '价税合计',
            key: 'priceTaxTotal',
            width: '7%',
            type: FormTypes.inputNumber,
            statistics: true,
            readonly: true,
          },
          { title: '备注', key: 'remark', width: '6%', type: FormTypes.input },
        ],
      },
      confirmLoading: false,
      validatorRules: {
        operTime: {
          rules: [{ required: true, message: '请输入单据日期!' }],
        },
        customerId: {
          rules: [{ required: true, message: '请选择客户!' }],
        },
        salespersonId: {
          rules: [{ required: true, message: '请选择客户!' }],
        },
        accountId: {
          rules: [{ required: true, message: '请选择结算账户!' }],
        },
      },
      url: {
        add: '/salesReturnOrder',
        edit: '/salesReturnOrder/update',
        detailList: '/depotItem/getDetailList',
      },
    }
  },
  created() {},
  methods: {
     handPurchaseChoose() {
      this.$refs.salesOrderChoose.show()
    },
     salesOrderChooseOk(record) {
      getAction('/salesOrder/one', { id: record.id }).then((res) => {
        this.materialTable.dataSource = res.data.salesDetailDTOList
        this.materialTable.dataSource.forEach((item, index) => {
          item.unitPrice = item.salesPrice
        })
        this.salesOrderNo = res.data.orderNo
        this.salesOrderId = res.data.id
        this.form.setFieldsValue({
          amountAfterDiscount: res.data.amountAfterDiscount, 
        })
      })
    },
    //调用完edit()方法之后会自动调用此方法
    editAfter() {
         this.salesOrderId=''
      this.salesOrderNo=""
      this.billStatus = '0'
      this.currentSelectDepotId = ''
      this.rowCanEdit = true
      this.materialTable.columns[1].type = FormTypes.popupJsh
      this.changeColumnHide()
      this.changeFormTypes(this.materialTable.columns, 'snList', 0)
      this.changeFormTypes(this.materialTable.columns, 'batchNumber', 0)
      this.changeFormTypes(this.materialTable.columns, 'expirationDate', 0)
      this.changeFormTypes(this.materialTable.columns, 'preNumber', 0)
      this.changeFormTypes(this.materialTable.columns, 'finishNumber', 0)
      if (this.action === 'add') {
        this.addInit(this.prefixNo)
        this.personList.value = ''
        this.fileList = []
      } else {
        this.model.operTime = this.model.orderDate
        this.$nextTick(() => {
          this.form.setFieldsValue(
            pick(
              this.model,
              'operTime',
              'orderNo',
              'orderDate',
              'deliveryDate',
              'customerAddress',
              'customerName',
              'discountRate',
              'salesAmount',
              'discountAmount',
              'amountAfterDiscount',
              'receivedAmount',
              'collectionStatus',
              'refundStatus',
              'accountingStatus',
              'isAudited',
              'debt',
              'salesExpense',
              'collectionArrivalDate',
              'paymentChannel',
              'deliveryMethod',
              'paymentTerms',
              'quantity',
              'remark',
              'prepaymentOrderId',
              'prepaymentOrderNo',
              'prepaymentAmount',
              'routeId',
              'routeName',
              'settlementAccountId',
              'settlementAccountName',
              'salesOrderId',
              'salesOrderNo',
              'customerId',
              'customerCategory',
              'salespersonId',
              'salespersonName',
              'auditorId',
              'auditorName',
              'logisticsId',
              'logisticsNo',
              'reReceivedAmount'
            )
          )
        })
         this.salesOrderId=this.model.salesOrderId
      this.salesOrderNo=this.model.salesOrderNo
        this.materialTable.dataSource = this.model.salesReturnDetailVOList
this.materialTable.dataSource.forEach((item, index) => {
          item.unitPrice = item.salesPrice
        })
      }
      //复制新增单据-初始化单号和日期
      if (this.action === 'copyAdd') {
        this.model.id = ''
        this.model.tenantId = ''
        this.copyAddInit(this.prefixNo)
      }
      this.initDeliveryMethod()
      this.initCustomer(0)
      this.initUser()
      this.initAccount(0)
    },
    //提交单据时整理成formData
    classifyIntoFormData(allValues) {
     let billMain = Object.assign(this.model, allValues.formValue)
      let detailArr = allValues.tablesValue[0].values
      for (let item of detailArr) {
        item.salesPrice = item.unitPrice
      }
      if (this.model.id) {
        billMain.id = this.model.id
      }
      billMain.salesOrderId=this.salesOrderId
      billMain.salesReturnDetailDTOList = detailArr
      billMain.orderDate = billMain.operTime
      return billMain
    },
    onSearchLinkNumber() {
      this.$refs.linkBillList.show('出库', '销售', '客户', '1,2,3')
      this.$refs.linkBillList.title = '请选择销售出库'
    },
    linkBillListOk(selectBillDetailRows, linkNumber, organId, discountMoney, deposit, remark) {
      this.rowCanEdit = false
      this.materialTable.columns[1].type = FormTypes.normal
      this.changeFormTypes(this.materialTable.columns, 'preNumber', 1)
      this.changeFormTypes(this.materialTable.columns, 'finishNumber', 1)
      if (selectBillDetailRows && selectBillDetailRows.length > 0) {
        let listEx = []
        let allTaxLastMoney = 0
        for (let j = 0; j < selectBillDetailRows.length; j++) {
          let info = selectBillDetailRows[j]
          if (info.finishNumber > 0) {
            info.operNumber = info.preNumber - info.finishNumber
            info.allPrice = info.operNumber * info.unitPrice - 0
            let taxRate = info.taxRate - 0
            info.taxAmount = ((info.allPrice * taxRate) / 100).toFixed(2) - 0
            info.taxLastMoney = (info.allPrice + info.taxAmount).toFixed(2) - 0
          }
          info.linkId = info.id
          allTaxLastMoney += info.taxLastMoney
          listEx.push(info)
          this.changeColumnShow(info)
        }
        this.materialTable.dataSource = listEx
        ///给优惠后金额重新赋值
        allTaxLastMoney = allTaxLastMoney ? allTaxLastMoney : 0
        let discount = 0
        if (allTaxLastMoney !== 0) {
          discount = ((discountMoney / allTaxLastMoney) * 100).toFixed(2) - 0
        }
        let discountLastMoney = (allTaxLastMoney - discountMoney).toFixed(2) - 0
        this.$nextTick(() => {
          this.form.setFieldsValue({
            organId: organId,
            linkNumber: linkNumber,
            discount: discount,
            discountMoney: discountMoney,
            discountLastMoney: discountLastMoney,
            changeAmount: discountLastMoney,
            remark: remark,
          })
        })
      }
    },
  },
}
</script>
<style scoped>
</style>